import React, { useCallback, useContext } from 'react'
import { Icon } from '@blueprintjs/core'
import classNames from 'classnames'
import PlayIcon from 'components/PlayIcon'
import { createMusic } from 'helpers/business'
import { ACTIONS, AudioCtx, PlayMusicContext } from 'reducers/playMusic'
import styles from './style.module.css'
import { formatTime } from 'helpers/time'
const Content = ({ data }) => {
  const [playState, playDispatch] = useContext(PlayMusicContext)
  const audioInfo = useContext(AudioCtx)
  const handleDoubleClick = useCallback(
    (i: number) => {
      const item = data[i]
      playDispatch({
        type: ACTIONS.PLAY,
        payload: {
          musicId: item.id,
          music: createMusic({
            ...item,
            duration: item.duration / 1000,
            picUrl: item.picUrl || item.album.blurPicUrl,
          }),
        },
      })
    },
    [data],
  )

  return (
    <div className={styles.root}>
      {data &&
        data.length &&
        data.map((v, i) => {
          const { id, name, artists, album, duration, picUrl } = v
          const isActive = playState.musicId === id
          return (
            <div className={styles.item} key={id} onDoubleClick={() => handleDoubleClick(i)}>
              <div className={classNames(styles.index, isActive && 'active')}>
                {isActive ? (
                  <Icon icon={audioInfo.state?.paused ? 'volume-off' : 'volume-up'} iconSize={15} />
                ) : (
                  <span>{i + 1}</span>
                )}
              </div>
              <div className={styles.musicInfo}>
                <div className={styles.pic}>
                  <img src={`${picUrl || album.blurPicUrl}?param=60y60`} className='cover' loading='lazy' />
                  <PlayIcon className={styles.playIcon} />
                </div>
                <div className={classNames(styles.name, isActive && 'active')}> {name} </div>
              </div>
              <div className={styles.artists}>{artists.map(({ name }) => name).join(' / ')}</div>
              <div className={styles.album}>{album.name}</div>
              <div className={styles.duration}>{formatTime(duration / 1000)}</div>
            </div>
          )
        })}
    </div>
  )
}
export default Content
